<template>
	<view class="page_body">
		<!-- 状态栏高度 设置背景色 占位状态栏-->
		<view class="ztl"
			:style="{'height':statusBarHeight}"></view>
		<!-- 占位盒子 -->
		<view class=""
			:style="{'height': hieght}"></view>
		<!-- 导航栏 -->
		<navBar bgColor="#FFF">
			<image :slot="'left'"
				@click='navToBack'
				:src="xcxImgUrl && xcxImgUrl+'fanhui.svg'"
				style="width: 36rpx;height: 36rpx;">
			</image>
			<text :slot="'content'">确认支付</text>
		</navBar>

		<scroll-view :style="{'height': 'calc(100vh - ' + demoTopHieght +')'}"
			scroll-y
			class="mian_surePay">

			<view class="main_surePay_top">
				<view class="main_surePay_top_money">
					￥{{Utils.formatToFixed(yinfuMoney*1,'money')}}
				</view>
				<view class="main_surePay_top_date ">
					<text class="mr10">支付剩余时间</text>

					<u-count-down v-if="computedPayDate != '不限制'"
						:time="computedPayDate"
						format="HH:mm:ss"
						autoStart
						millisecond
						@change="onChange">
						<view class="time">
							<view class="time__custom">
								<text
									class="time__custom__item">{{ timeData.hours >= 10 ? timeData.hours : '0' + timeData.hours}}</text>
							</view>
							<text class="time__doc">:</text>
							<view class="time__custom">
								<text
									class="time__custom__item">{{ timeData.minutes >= 10 ? timeData.minutes : '0' + timeData.minutes }}</text>
							</view>
							<text class="time__doc">:</text>
							<view class="time__custom">
								<text
									class="time__custom__item">{{ timeData.seconds >= 10 ? timeData.seconds : '0' + timeData.seconds}}</text>
							</view>
						</view>
					</u-count-down>
					<text v-else>不限制</text>
				</view>
			</view>

			<view class="main_surePay_top_select">
				<view class="main_surePay_top_select_title pd_left10">
					选择支付方式
				</view>
				<view v-if="[1,4,5,7].includes(computedPayStatus) && (computedWeixinPay || computedFuyouPay || computedTonglianPay)"
					class="main_surePay_top_select_item" @click="checkedIndex = 1">
					<view class="main_surePay_top_select_item_l pd_left10">
						<image class="pd_lr10"
							:src="xcxImgUrl && xcxImgUrl+'page_public/static/weixinzhifu.svg'"></image>
						<text>微信支付</text>
					</view>
					<view class="">
						<!-- <checkbox @click="checkedSure(1)" :checked="checkedIndex == 1" color="#ec4141"
							style="transform:scale(0.7);border-radius: 50%;"></checkbox> -->
						<view class="custom_checkbox"
							:class="{active : checkedIndex == 1}">
							<u-checkbox-group :value="[checkedIndex == 1]"
								@change="checkedSure(1)">
								<u-checkbox :name="true"></u-checkbox>
							</u-checkbox-group>
						</view>
					</view>
				</view>
				<!-- <view class="main_surePay_top_select_item">
					<view class="main_surePay_top_select_item_l pd_left10">
						<image class="pd_lr10" src="./static/zhifubaozhifu.svg" ></image>
						<text>支付宝支付</text>
					</view>
					<view class="">
						<checkbox 
						color="#ec4141"
						style="transform:scale(0.7);border-radius: 50%;"></checkbox>
					</view>
				</view> -->
				<!-- <view v-if="[1,4,5,7].includes(computedPayStatus) && computedFuyouPay"
					class="main_surePay_top_select_item">
					<view class="main_surePay_top_select_item_l pd_left10">
						<image class="pd_lr10" :src="xcxImgUrl && xcxImgUrl+'page_public/static/newfouyouzhifu.svg'"></image>
						<text>富友支付</text>
					</view>
					<view class="">
						
							style="transform:scale(0.7);border-radius: 50%;"></checkbox> -->
						<!-- <view class="custom_checkbox"
							:class="{active : checkedIndex == 2}">
							<u-checkbox-group :value="[checkedIndex == 2]"
								@change="checkedSure(2)">
								<u-checkbox :name="true"></u-checkbox>
							</u-checkbox-group>
						</view>
					</view>
				</view> --> 
				<!-- <view 
				v-if="[1,4,5,7].includes(computedPayStatus) && computedTonglianPay"
				class="main_surePay_top_select_item">
					<view class="main_surePay_top_select_item_l pd_left10">
						<image class="pd_lr10"  :src="xcxImgUrl && xcxImgUrl+'page_public/static/fuyoutonglianzhifu.svg'"></image>
						<text>通联支付</text>
					</view>
					<view class="">
						<view class="custom_checkbox"
							:class="{active : checkedIndex == 3}">
							<u-checkbox-group :value="[checkedIndex == 3]"
								@change="checkedSure(3)">
								<u-checkbox :name="true"></u-checkbox>
							</u-checkbox-group>
						</view>
					</view>
				</view> -->
				<view v-if="[3,5,6,7].includes(computedPayStatus) && computedCuxiaoOrderStatus"
					class="main_surePay_top_select_item" @click="checkedIndex = 4">
					<view class="main_surePay_top_select_item_l pd_left10">
						<image class="pd_lr10"
							:src="xcxImgUrl && xcxImgUrl+'page_public/static/xianxiazhifu.svg'"></image>
						<text>线下支付</text>
					</view>
					<view class="">
						<!-- <checkbox @click="checkedSure(4)" :checked="checkedIndex == 4" color="#ec4141"
							style="transform:scale(0.7);border-radius: 50%;"></checkbox> -->
						<view class="custom_checkbox"
							:class="{active : checkedIndex == 4}">
							<u-checkbox-group :value="[checkedIndex == 4]"
								@change="checkedSure(4)">
								<u-checkbox :name="true"></u-checkbox>
							</u-checkbox-group>
						</view>
					</view>
				</view>
				<view v-if="[2,4,6,7].includes(computedPayStatus) && computedCuxiaoOrderStatus"
					class="main_surePay_top_select_item" @click="checkedIndex = 5">
					<view class="main_surePay_top_select_item_l pd_left10">
						<image class="pd_lr10"
							:src="xcxImgUrl && xcxImgUrl+'page_public/static/guazhangzhifu.svg'"></image>
						<text>挂账支付</text>
					</view>
					<view class="">
						<!-- <checkbox @click="checkedSure(5)" :checked="checkedIndex == 5" color="#ec4141"
							style="transform:scale(0.7);border-radius: 50%;"></checkbox> -->
						<view class="custom_checkbox"
							:class="{active : checkedIndex == 5}">
							<u-checkbox-group :value="[checkedIndex == 5]"
								@change="checkedSure(5)">
								<u-checkbox :name="true"></u-checkbox>
							</u-checkbox-group>
						</view>
					</view>
				</view>
			</view>

			<view @click="surePay"
				style="margin-top: 50rpx;">
				<newBtn bgColor="#ec4141"
					color="#fff"
					name="确认支付"></newBtn>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import newBtn from '@/components/newBtn/newBtn.vue'
	import {
		createMallOrderMoney,
		wxPreCreate,
		getpaymentDetails,
		weixinPreCreate,
		tonglianPreCerate
	} from '@/api/global.js'
	// import wx from 'weixin-js-sdk'
	export default {
		computed: {
			...mapGetters(['demoTopHieght']),
			//返回支付状态显示对应的操作
			computedPayStatus() {
				// 1：在线支付 2：挂账支付 3：线下支付 4：在线支付+挂账支付 5：在线支付+线下支付 6：挂账支付+线下支付 7.全选
				return this.$store?.state?.configSetting?.payStatus * 1
			},
			//返回促销订单仅在线支付
			computedCuxiaoOrderStatus() {
				if (this.type == 1) { //促销订单
					//读取促销订单设置 1.false 2.true
					return this.$store?.state?.configSetting?.cuxiaoOrderPay == 1 ? false : true
				} else {
					return true
				}
			},
			//返回微信设置
			computedWeixinPay() {
				let res = this.$store?.state?.configSetting?.weixinPay && JSON.parse(this.$store?.state?.configSetting
					?.weixinPay)
				return res?.status == 1 ? true : false
			},
			//返回通联设置
			computedTonglianPay() {
				let res = this.$store?.state?.configSetting?.tonglianPay && JSON.parse(this.$store?.state?.configSetting
					?.tonglianPay)
					console.log(this.$store?.state?.configSetting?.tonglianPay,'通联')
				return res?.status == 1 ? true : false
			},
			//返回富友设置
			computedFuyouPay() {
				let res = this.$store?.state?.configSetting?.fuyouPay && JSON.parse(this.$store?.state?.configSetting
					?.fuyouPay)
				console.log(res,'res')
				return res?.status == 1 ? true : false
				// return true
			},
			//返回订单支付倒计时开始时间
			computedPayDate() {
				let youxiaoshichang = ''
				// 根据设置获取有效时长
				if (this.$store?.state?.configSetting?.payDate == 0) { //不限制
					return '不限制'
				} else if (this.$store?.state?.configSetting?.payDate == 1) { //5分钟
					youxiaoshichang = 5
				} else if (this.$store?.state?.configSetting?.payDate == 2) { //10分钟
					youxiaoshichang = 10
				} else if (this.$store?.state?.configSetting?.payDate == 3) { //30分钟
					youxiaoshichang = 30
				} else if (this.$store?.state?.configSetting?.payDate == 4) { //两小时
					youxiaoshichang = 2 * 60
				} else if (this.$store?.state?.configSetting?.payDate == 5) { //12小时
					youxiaoshichang = 12 * 60
				} else if (this.$store?.state?.configSetting?.payDate == 6) { //24小时
					youxiaoshichang = 24 * 60
				}
				console.log(youxiaoshichang);
				//获取创建时间 时间戳
				let createTime = ''
				if (this.time == '') {
					createTime = new Date().getTime()
				} else {
					createTime = new Date(this.time).getTime()
				}
				console.log(createTime);
				//获取当前时间的时间戳
				let nowTime = new Date().getTime()
				console.log(nowTime);
				//获取创建时间到当前时间的时间差
				let countSecond = parseInt((nowTime - createTime))
				console.log(countSecond);
				//有效时间减去时间差 得到剩余倒计时时间
				let times = youxiaoshichang * 60 * 1000 - countSecond
				console.log(times);
				if (times <= 0) {
					uni.navigateTo({
						url: `/pages/myde/myde`
					})
				}
				return times


			}
		},
		components: {
			newBtn
		},
		data() {
			return {
				paySign:'',
				signType:'',
				packages:'',
				nonceStr:'',
				timeStamp:'',
				code:'',
				status:'',
				types:'',
				statusBarHeight: '',
				hieght: '',
				type: 1, //区分是从哪个购物车页面过来的 1.活动 2.普通
				timeData: {}, //倒计时
				yinfuMoney: 0, //应付金额
				time: '', //从待付款近 time
				checkedIndex: 0, //1.微信 2.富友 3.通联 4.线下 5.挂账
				orderId: '', //订单id
			};
		},
		onLoad(options) {
			//区分是从哪个购物车页面过来的 1.活动 2.普通
			this.type = options?.type || 1
			this.yinfuMoney = options?.yinfuMoney || 0
			this.time = options?.time || ''
			this.orderId = options?.orderId || '';
			this.$store.dispatch('configSetting/getSetting');
			console.log(this.$store.state)
			this.getPaymentWay()
			console.log(this.$store?.state?.configSetting?.payStatus);
		},
		onShow() {
			this.$nextTick(() => {
				// 获取状态栏的高度
				this.statusBarHeight = this.$store.state.statusBarHeight * 2 + 'rpx'
				// 计算站位的高度
				this.hieght = (this.$store.state.navBarHeight) * 2 + 'rpx'
				//获取高度
				this.Utils.getDemoTopHeight('mian_surePay')
				console.log(123);

			})
		},
		methods: {
			// 获取支付方式
			async  getPaymentWay(){
			 let {data} = await getpaymentDetails()
			 this.types = data.info.type
			 // this.status = data.info.status
			},
			//返回上一页
			navToBack() {
			   console.log(111111);
				uni.switchTab({
				                    url:'/pages/myde/myde'
				                })
			},
			//倒计时
			onChange(e) {
				this.timeData = e
			},
			//选择支付方式
			checkedSure(index) {
				// 1.微信 2.富友 3.通联 4.线下 5.挂账
				this.checkedIndex = index
			},
			//确认支付
			async surePay() {

				//校验是否选择支付方式
				if (this.checkedIndex == 0) {
					this.Utils.toast('请选择支付方式')
					return
				}

				//根据选择的支付方式 取需要的支付参数 给生成支付接口
				let payType = ''
				let subjectId = ''
				if (this.checkedIndex == 1) {
					payType = 1
					subjectId = JSON.parse(this.$store?.state?.configSetting?.weixinPay)?.subjectId
				} else if (this.checkedIndex == 2) {
					payType = 3
					subjectId = JSON.parse(this.$store?.state?.configSetting?.fuyouPay)?.subjectId
				} else if (this.checkedIndex == 3) {
					payType = 2
					subjectId = JSON.parse(this.$store?.state?.configSetting?.tonglianPay)?.subjectId
				} else if (this.checkedIndex == 4) {
					payType = 4
				} else if (this.checkedIndex == 5) {
					payType = 5
				}

				//生成支付记录
				let res = await createMallOrderMoney({
					payType: payType, //支付类型【1:微信支付 2:通联支付 3:富友支付 4:线下支付 5:挂账支付】
					money: this.yinfuMoney,
					// money:0.01,
					subjectId: subjectId, //会计科目id[关联会计科目表]
					orderId: this.orderId, //订单id
				})
				//生成支付记录成功
				if (res.code == 2000) {
					//如果是线下 跳转页面
					if (this.checkedIndex == 4) {
						uni.navigateTo({
							url: `/page_public/offlinePay?yinfuMoney=${this.yinfuMoney}&orderId=${this.orderId}`
						})
					}
					//如果是挂账支付 生成支付记录就是支付成功 跳转页面
					else if (this.checkedIndex == 5) {
						uni.navigateTo({
							url: '/page_public/successPay'
						})
					} else { //线上支付
						// //获取openid
						// let openid = this.$store.state.gzhOpenId 
						let openid = uni.getStorageSync('wxOpenId') || this.$store.state.openId
						console.log(openid, res);
						//调用支付 获取签名
						if(this.types == 10 ) {
							let rescon = await wxPreCreate({
								moneyId: res?.data?.code || '', //
								// trade_type:'JSAPI', //jsapi
								trade_type: 'LETPAY', //小程序
								sub_openid: openid,
							})
							console.log(rescon, '签名352', uni.getStorageSync('wxOpenId'));
							let a = rescon?.data?.info?.sdk_timestamp;
							// let {
							// 	sdk_timestamp: timeStamp,
							// 	sdk_noncestr: nonceStr,
							// 	sdk_package: packages,
							// 	sdk_signtype: signType,
							// 	sdk_paysign: paySign
							// } = rescon.data.info;
							this.code = rescon.code
							this.timeStamp = rescon.data.info.sdk_timestamp
							this.nonceStr = rescon.data.info.sdk_noncestr
							this.packages = rescon.data.info.sdk_package
							this.signType = rescon.data.info.sdk_signtype
							this.paySign =  rescon.data.info.sdk_paysign
						}
						// 通联支付
						console.log(this.types);
						if(this.types == 9 ) {
							let rescon = await tonglianPreCerate({
								moneyId: res?.data?.code || '', //
								// trade_type:'JSAPI', //jsapi
								payType: 'W06', //小程序
								acct: openid,
							})
							this.code = rescon.code
							console.log(rescon,'通联支付');
							console.log(rescon.data.info.payinfo,'通联支付');
							const payinfo = JSON.parse(rescon.data.info.payinfo)
							this.timeStamp = payinfo.timeStamp
							this.nonceStr = payinfo.nonceStr
							this.packages = decodeURIComponent(payinfo.package)
							this.signType = payinfo.signType
							this.paySign =  decodeURIComponent(payinfo.paySign)
					
						}
						if(this.types == 8 ) {
							let rescon = await weixinPreCreate({
								moneyId: res?.data?.code || '', //
								openid: openid,
							})
							this.code = rescon.code
							console.log(rescon,'微信支付');
							console.log(rescon.data.info.payinfo,'通联支付');
							const payinfo = JSON.parse(rescon.data.info.payinfo)
							this.timeStamp = payinfo.timeStamp
							this.nonceStr = payinfo.nonceStr
							this.packages = decodeURIComponent(payinfo.package)
							this.signType = payinfo.signType
							this.paySign =  decodeURIComponent(payinfo.paySign)
											
						}
						if (this.code == 2000) {
							console.log(111111);
							//调起支付 jsapi
							// WeixinJSBridge.invoke(
							//      'getBrandWCPayRequest', {
							//         "appId":rescon?.data?.info?.sdk_appid || '',     //公众号ID，由商户传入     
							//         "timeStamp":rescon?.data?.info?.sdk_timestamp || '',         //时间戳，自1970年以来的秒数     
							//         "nonceStr":rescon?.data?.info?.sdk_noncestr || '', //随机串     
							//         "package":rescon?.data?.info?.sdk_package || '',     
							//         "signType":rescon?.data?.info?.sdk_signtype || '',         //微信签名方式：     
							//         "paySign":rescon?.data?.info?.sdk_paysign || '' //微信签名 
							//      },
							//      (res)=>{
							//      if(res.err_msg == "get_brand_wcpay_request:ok" ){
							//      // 使用以上方式判断前端返回,微信团队郑重提示：
							//      //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
							//   alert('支付成功')
							//      } 
							//   }); 
							// let a = rescon?.data?.info?.sdk_package
							// let b = a.substr(a.indexOf('=')+1)
							//跳转微信 调用微信的支付
							// let params= '?timestamp='+encodeURIComponent(rescon?.data?.info?.sdk_timestamp) +
							// '&nonceStr='+encodeURIComponent(rescon?.data?.info?.sdk_noncestr)  + 
							// '&package='+encodeURIComponent(rescon?.data?.info?.sdk_package) + 
							// '&signType='+encodeURIComponent(rescon?.data?.info?.sdk_signtype)  + 
							// '&paySign='+encodeURIComponent(rescon?.data?.info?.sdk_paysign)
							// // 传入参数除了必须的支付参数，也可以自行添加后续回调用到的参数，但是要注意微信小程序的参数有长度限制，确认params长度是否能全部传入
							// const url = '../webViewPay/webViewPay'+params;
							// wx.miniProgram.navigateTo({
							//    url: url
							// });
							console.log('支付参数',this.timeStamp,this.nonceStr,this.packages,this.signType,this.paySign,)
							wx.requestPayment({
								timeStamp:this.timeStamp,
								nonceStr:this.nonceStr,
								package: this.packages,
								signType:this.signType,
								paySign:this.paySign,
								success(res) {
									if (res.errMsg == "requestPayment:ok") {
										// let pages = getCurrentPages();
										// let prev = pages[pages.length - 2];
										// prev.$vm.pay = 'pay';
										// uni.navigateBack();
										uni.switchTab({
											url: `/pages/myde/myde`
										})
									} else if (res.errMsg == 'requestPayment:cancel') {
										uni.showToast({
											title: `取消支付`
										})
									}
								},
								fail(res) {
									uni.showToast({
										title: `支付失败`
									})
								}
							})
						} else {
							this.Utils.toast(`${rescon.msg}`)
						}



					}
				} else { //生成支付记录失败
					this.Utils.toast(`${res.msg}`)
				}
			},

		}
	}
</script>

<style lang="scss"
	scoped>
	.mian_surePay {
		box-sizing: border-box;
		width: 100%;

		.main_surePay_top {
			width: 100%;
			height: 240rpx;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: space-evenly;

			.main_surePay_top_money {
				font-size: 48rpx;
				font-weight: bold;
				color: $text_color_333;
			}

			.main_surePay_top_date {
				font-size: $font_size_12;
				color: $text_color_808080;
				display: flex;
				align-items: center;

			}
		}

		.main_surePay_top_select {
			width: 90%;
			margin: 0 auto;
			background-color: #FFF;
			border-radius: $border_radius_10;

			.main_surePay_top_select_title {
				width: 100%;
				height: 88rpx;
				font-size: $font_size_14;
				color: $text_color_333;
				line-height: 88rpx;
				border-bottom: 1px solid #f3f3f3;
			}

			.main_surePay_top_select_item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: 100%;
				height: 120rpx;
				border-bottom: 1px solid #f3f3f3;

				.main_surePay_top_select_item_l {
					display: flex;
					align-items: center;
					font-size: $font_size_14;
					color: $text_color_333;

					image {
						width: 60rpx;
						height: 60rpx;
					}
				}
			}
		}
	}

	.time {
		@include flex;
		align-items: center;

		&__custom {
			// margin-top: 4px;
			width: 22px;
			height: 22px;
			background-color: rgba(128, 128, 128, 1);
			border-radius: 4px;
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			justify-content: center;
			align-items: center;

			&__item {
				color: #fff;
				font-size: 12px;
				text-align: center;
			}
		}

		&__doc {
			color: rgba(128, 128, 128, 1);
			padding: 0px 4px;
		}

		&__item {
			color: #606266;
			font-size: 15px;
			margin-right: 4px;
		}
	}
</style>